import Vue from 'vue'
import Vuex from 'vuex'

import { login } from '@/api/user'

import user from './modules/user'
import { saveToken, getToken } from '../utils/storage'

Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    tokenInfo: getToken() || {}
  },
  mutations: {
    // 将token存储到 vuex 中
    setTokenInfo (state, newTokenInfo) {
      state.tokenInfo = newTokenInfo
      // 保存到本地localstorage
      saveToken(newTokenInfo)
    }
  },
  actions: {
    // 发送请求
    async userLogin (context, userInfo) {
      try {
        const res = await login(userInfo)
        console.log(res.data.data)
        context.commit('setTokenInfo', res.data.data)
      } catch (err) {
        console.log(err)
        // 将错误抛给 doLogin
        throw new Error(err)
      }
    }

  },
  modules: {
    user
  }
})
